package com.kzw.oa.comm.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.kzw.core.orm.Page;
import com.kzw.core.orm.PageRequest;
import com.kzw.core.orm.StringPropertyFilter;
import com.kzw.core.service.hibernate.DefaultEntityManager;
import com.kzw.core.util.DateUtil;
import com.kzw.misc.utils.ContextUtil;
import com.kzw.oa.comm.model.TongBao;
import com.kzw.oa.system.model.Department;
import com.kzw.oa.system.service.DepartmentService;

@Service
@Transactional
public class TongBaoService extends DefaultEntityManager<TongBao, Long> {
	
	@Autowired
	private DepartmentService deptService;

	public List<TongBao> listMy() {
		return listMy(null);
	}
	
	public List<TongBao> listMy(List<StringPropertyFilter> filters) {
		// 1、设置失效（expTime为null是否正常？）
		String hql = "update TongBao set status=0 where expTime<=?";
		getEntityDao().batchExecute(hql, DateUtil.strToDate());
		
		// 2、构建查询条件
		if(filters == null) {
			filters = new ArrayList<StringPropertyFilter>();
		}
		filters.add(new StringPropertyFilter("EQI_status", "1"));
		
		// 显示最新的8条记录
		PageRequest pageRequest = new PageRequest(8);
		pageRequest.setOrderBy("ctime");
		pageRequest.setOrderDir("desc");
		Page<TongBao> page = search2(pageRequest, filters);
		
		// 3、判断本单位可见
		Department dept = ContextUtil.getCurrentDept();
		List<TongBao> list = new ArrayList<TongBao>();
		for(TongBao tb : page.getData()) {
			// downDeptShow=1：下级单位可见
			String deptIds = tb.getRecDepIds();
			
			// 如果没有指定接收单位，则可见
			if(StringUtils.isBlank(deptIds)) {
				list.add(tb);
				continue;
			}
			
			if(deptIds.startsWith(",")) {
				deptIds = deptIds.substring(1);				
			}
			if(deptIds.endsWith(",")) {
				deptIds = deptIds.substring(0, deptIds.length()-1);
			}
			String[] ids = deptIds.split(",");
			for(String id : ids) {
				Department tbDept = deptService.get(Long.parseLong(id));
				
				if(tb.getDownDeptShow() == 1) {
					if(dept.getPath().startsWith(tbDept.getPath())) {
						list.add(tb);
						break;
					}
				}
				if(tbDept.getPath().equals(dept.getPath())) {
					list.add(tb);
					break;
				}
			}			
		}
		return list;
	}
}
